
package com.link.base.core.basic.filter;

import com.link.core.cllog.LCLogger;
import com.link.core.util.PasswordUtil;
import com.link.microservice.AuthClient;
import org.apache.commons.lang.StringUtils;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "websocketFilter", urlPatterns = "/websocket/*", asyncSupported = true)
public class WebSocketFilter implements Filter {

    @Resource
    private AuthClient authClient;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {


    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        String token = request.getParameter("token");
        LCLogger.info().withMessageKey("WebSocketFilter.doFilter").withMessage("token -> " + token).flush();
        if (StringUtils.isBlank(token)) {
            ((HttpServletResponse) response).sendError(403, "Forbidden Access!Token can not be null!");
            return;
        }
        try {
            String decryptToken = PasswordUtil.decryptString(token);
            if (StringUtils.isBlank(decryptToken)) {
                ((HttpServletResponse) response).sendError(403, "Forbidden Access!Token can not be null!");
                return;
            }
            String newToken = "bearer " + decryptToken;
            LCLogger.info().withMessageKey("WebSocketFilter.doFilter").withMessage("newToken -> " + newToken).flush();
            String ret = authClient.checkToken(newToken);
            LCLogger.info().withMessageKey("WebSocketFilter.doFilter").withMessage("ret -> " + ret).flush();
            if (ret == null || "".equals(ret)) {
                ((HttpServletResponse) response).sendError(403, "Forbidden Access!Token Error!");
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
            ((HttpServletResponse) response).sendError(403, "Forbidden Access!Token Error!");
            return;
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {


    }

}

